<?php

class JdRankLog{

	/**
	 * 添加
	 *
	 */
	function add($data){
		
		$m = M('JdRankLog');
		//返回自增id
		$id = $m->add($data);
		
		return $id;
	}

	/**
	 * 修改
	 *
	 */
	function update_by_id($id,$upItems){
		$m = M('JdRankLog');
		return $m -> where('id='.$id)->save($upItems);
	}
	
	function get_by_id($id){
		$m = M('JdRankLog');
		return $m -> getById($id);
	}

    function delete_by_rank_id($rank_id){
        $m = M('JdRankLog');
        return $m -> where("rank_id=".$rank_id)->delete();
    }

	function get_by_rank_id($rank_id){
		
		$m = M('JdRankLog');
		return $m->where('rank_id='.$rank_id)
            ->order('created DESC')
		->select();
	}

    function get_by_created($created){

        $m = M('JdRankLog');
        return $m->where('admin_id='.$admin_id)
            ->order('created DESC')
            ->select();
    }

    /**
     * 获取指定的id的记录
     * @param $ids
     * @return mixed
     */
    function get_by_ids($ids){

        $m = M('JdRankLog');
        return $m->table('jd_rank_log')
            ->where("rank_id IN ($ids)")
            ->field("rank_id,rank,DATE_FORMAT(created,'%Y-%m-%d') AS created")
            ->order('rank_id ASC')
            ->select();
    }

    /**
     * 分组排名数据
     * @param $logs
     * @return array
     */
    function group_logs($logs){

        $ids = array();

        foreach($logs as $l){

            $rank_id = $l['rank_id'];
            $created = $l['created'];
            $rank    = $l['rank'];

            $ids[$rank_id][$created] = $rank;

        }

        return $ids;
    }

    /**
     * 按日期添加
     * @param $id
     * @param $rank
     * @param null $date
     */
    function add_by_created($id,$rank,$date = null){

        if(is_null($date)){
            $date = date('Y-m-d');
        }

        $m = M('JdRankLog');
        $exists_log =  $m->table('jd_rank_log')
            ->where("DATE_FORMAT(created,'%Y-%m-%d') = '$date' AND rank_id = $id")
            ->getField("COUNT(*)");

        //不存在则添加
        if($exists_log == 0){
            $this->add(array(
                'rank_id'   =>$id,
                'rank'      =>$rank,
                'created'   =>full_date()
            ));
        }
    }
}